package com.mhtvs;


import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.content.Context;
import com.mhtvs.MhtvsActivity;
import com.mhtvs.R;
import com.mhtvs.Database.PortForwards;

//---------------------------------------------------------------
//Development source for MHTVS CLIENT
//"Android client for use with MHTVS"
//Copyright (c) 2011, Doug Thompson, perladdict@gmail.com
//All rights reserved.
//
//http://code.google.com/p/mhtvs/
//
//View Demo here:
//http://www.youtube.com/watch?v=v4M2uVrMrGk
//
//Redistribution and use in source and binary forms, with or
//without modification, are permitted provided that the following
//conditions are met:
//
//* Redistributions of source code must retain the above
//  copyright notice, this list of conditions and the
//  following disclaimer.
//* Redistributions in binary form must reproduce the
//  above copyright notice, this list of conditions and
//  the following disclaimer in the documentation and/or
//  other materials provided with the distribution.
//* Neither the name of the developer nor the names
//  of its contributors may be used to endorse or promote
//  products derived from this software without specific
//  prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
//CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
//INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
//MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
//CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
//SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
//INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
//OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
//SUCH DAMAGE.
//---------------------------------------------------------------


// Server Entry Screen
public class PortForwardsEntry extends MhtvsActivity {
	protected static final String PREFS_PRIVATE = null;
	protected static final String KEY_PRIVATE = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.server_portforward_view);
		final Button saveServer = (Button) findViewById(R.id.ButtonAddPortForwards);
		
		saveServer.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				final EditText LocalPortForward = (EditText) findViewById(R.id.LocalPortNumber);
				final EditText RemotePortForward = (EditText) findViewById(R.id.RemotePortNumber);
				SQLiteDatabase db = mDatabase.getWritableDatabase();
				db.beginTransaction();
				try {
					// INSERT INTO PORTFORWARDS TABLE
					ContentValues ServerRecordToAdd = new ContentValues();
					SharedPreferences prefsPrivate = getSharedPreferences(PREFS_PRIVATE, Context.MODE_PRIVATE);
					int PASSED_ID_KEY = Integer.parseInt(prefsPrivate.getString(KEY_PRIVATE, "serverid"));
					ServerRecordToAdd.put(PortForwards.PORTFORWARDS_ID_KEY, PASSED_ID_KEY);
					ServerRecordToAdd.put(PortForwards.PORTFORWARDS_LOCAL, Integer.parseInt(LocalPortForward.getText().toString()));
					ServerRecordToAdd.put(PortForwards.PORTFORWARDS_REMOTE, Integer.parseInt(RemotePortForward.getText().toString()));
					db.insert(PortForwards.PORTFORWARDS_TABLE_NAME, PortForwards.PORTFORWARDS_ID_KEY,ServerRecordToAdd);
					db.setTransactionSuccessful();
				} finally {
					db.endTransaction();
				}
				// reset form
				LocalPortForward.setText(null);
				RemotePortForward.setText(null);
				db.close();
				startActivity(new Intent(getApplicationContext(), PortForwardsEntry.class));	
			}
		});
		// Handle Go to List button
		final Button gotoList = (Button) findViewById(R.id.ButtonShowList);
		gotoList.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// Go to other activity that displays pet list
				startActivity(new Intent(getApplicationContext(), ListServers.class));
			}
		});
		fillPortList();
	}
	
    // DIALOG SETUPS
	// http://developmentality.wordpress.com/2009/10/31/android-dialog-box-tutorial/
	public interface Command {
		public void execute();
		public static final Command NO_OP = new Command() { public void execute() {} };
	}
	
	public static class CommandWrapper implements DialogInterface.OnClickListener {
		  private Command command;
		  public CommandWrapper(Command command) {
		    this.command = command;
		  }

		  @Override
		  public void onClick(DialogInterface dialog, int which) {
		    dialog.dismiss();
		    command.execute();
		  }
	}
	    
	private static final CommandWrapper DISMISS = new CommandWrapper(Command.NO_OP);

	public static AlertDialog createDeletionDialog(final Context context, final Command deleteCommand) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setCancelable(true);
		//builder.setIcon(R.drawable.dialog_question);
		builder.setTitle("Confirm deletion?");
		builder.setInverseBackgroundForced(true);
		builder.setPositiveButton("Delete", new CommandWrapper(deleteCommand));
		builder.setNegativeButton("Dismiss", DISMISS);
		return builder.create();
	}
		
	public void fillPortList() {
		// TableLayout where we want to Display list
		final TableLayout portTable = (TableLayout) findViewById(R.id.TableLayout_PortList);
		// SQL Query
		SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
		SharedPreferences prefsPrivate = getSharedPreferences(PREFS_PRIVATE, Context.MODE_PRIVATE);
		int PASSED_ID_KEY = Integer.parseInt(prefsPrivate.getString(KEY_PRIVATE, "serverid"));
		queryBuilder.setTables(PortForwards.PORTFORWARDS_TABLE_NAME);
		String inWhere = PortForwards.PORTFORWARDS_ID_KEY + " = " + PASSED_ID_KEY;
		queryBuilder.appendWhere(inWhere);
		// Get the database and run the query
        SQLiteDatabase db = mDatabase.getReadableDatabase();
        String asColumnsToReturn[] = { 
        		PortForwards.PORTFORWARDS_TABLE_NAME + "." + PortForwards.PORTFORWARDS_LOCAL, 
        		PortForwards.PORTFORWARDS_TABLE_NAME + "." +PortForwards.PORTFORWARDS_REMOTE, 
        		PortForwards.PORTFORWARDS_TABLE_NAME + "." + PortForwards.PORTFORWARDS_ID_KEY,
        		PortForwards.PORTFORWARDS_TABLE_NAME + "." + PortForwards.PORTFORWARDS_ID
        };

       final Cursor c = queryBuilder.query(db, asColumnsToReturn, null, null, null, null, PortForwards.DEFAULT_SORT_ORDER);
       // Display the results by adding some TableRows to the existing table layout
		if(c.moveToFirst()) {
			for(int i = 0; i< c.getCount(); i++) {
				TableRow newRow = new TableRow(this);
				TextView portforward_local = new TextView(this);
				TextView portforward_remote = new TextView(this);
				Button deleteButton = new Button(this);
				deleteButton.setText("remove portforward");
				deleteButton.setTextSize(8);
			    deleteButton.setMaxHeight(10);
				deleteButton.setTag(c.getInt(c.getColumnIndex(PortForwards.PORTFORWARDS_ID)));			
				deleteButton.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(final View v) {		
					    Command delete = new Command() {
					    	public void execute() {
					    		// Delete port entry
								Integer id = (Integer) v.getTag();
								deletePort(id);
								final TableLayout portTable = (TableLayout) findViewById(R.id.TableLayout_PortList);
								View viewToDelete = portTable.findViewWithTag(id);
								portTable.removeView(viewToDelete);
						    }
					    };
					    AlertDialog deletionDialog = PortForwardsEntry.createDeletionDialog(PortForwardsEntry.this, delete);
					    deletionDialog.show();
					}
				});
				newRow.setTag(c.getInt(c.getColumnIndex(PortForwards.PORTFORWARDS_ID)));
				portforward_local.setTextSize(10);
				portforward_remote.setTextSize(10);				
				portforward_local.setText("Local: " + String.valueOf(c.getInt(c.getColumnIndex(PortForwards.PORTFORWARDS_LOCAL))));
				portforward_remote.setText("Remote: " + String.valueOf(c.getInt(c.getColumnIndex(PortForwards.PORTFORWARDS_REMOTE))));		
				newRow.addView(deleteButton);
				newRow.addView(portforward_local);
				newRow.addView(portforward_remote);
				portTable.addView(newRow);
				c.moveToNext();
			}
		} else {
			TableRow newRow = new TableRow(this);
			TextView noResults = new TextView(this);
			noResults.setTextSize(8);
            noResults.setText("No current port entries.");
			newRow.addView(noResults);
			portTable.addView(newRow);
		}
		c.close();
		db.close();	
	}
	
	// http://stackoverflow.com/questions/4426891/android-appwidget-sharedpreferences-crash
	public static Context ctx;
	private final static String saved_pref_file="saved_port_prefs";
 
	public static void saveStringValue(String sName, String sValue, Context ctx) {
        SharedPreferences settings = ctx.getSharedPreferences(saved_pref_file, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(sName, sValue);
        editor.commit();
   }
	
    public static String loadStringValue(String sName, Context ctx) {
        try {
            SharedPreferences settings = ctx.getSharedPreferences(saved_pref_file, 0);
            return settings.getString(sName,"");
        } catch (Exception ex) {    return "";      }
    }
    
	public void deletePort(Integer id) {
        SQLiteDatabase db = mDatabase.getWritableDatabase();
		String astrArgs[] = { id.toString() };
        db.delete(PortForwards.PORTFORWARDS_TABLE_NAME, PortForwards.PORTFORWARDS_ID + "=?",astrArgs );
        db.close();
	}
	
}